//
//  DearViewController.m
//  Dear
//
//  Created by 陈俊俊 on 15/7/11.
//  Copyright (c) 2015年 陈俊俊. All rights reserved.
//

#import "DearViewController.h"
#import "SexViewController.h"
#import "LocViewController.h"
#import "LocPathViewController.h"
#import "TPFileManager.h"
//#import "LocationTool.h"
#import "UploadRequest.h"
#import "CustomButton.h"
#define HeadHeight 200
#define BtnHeight 120

#define TopHeight 50
#define LeftMargin 20
#define TextFieldHeight 44
#define LeftWidth 80
#define RelWidth  60
#define RelHeight  30


#define ImageHeight 40

#define SpaceMargin 10
//按钮的tag
typedef enum {
    WhereTag = 2001,
    LookTag ,
    SexesTag,
    EmotionalTag,
    RelationTag
} Tag;

@interface DearViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,LocationGetAddressDelegate,UITextFieldDelegate>
{
    UIImageView *_headImageView;
    UIScrollView *_btnView;
    CustomButton *_whereBtn;
    UIButton *_lookBtn;
    UIButton *_sexesBtn;
    UIButton *_emotionalBtn;
    
    UIImageView *_headView;
    UITextField *_relTextField;
    UIButton *_relBtn;
    UIImageView *locationImage;
    UILabel *_locationLabel;
    UIActivityIndicatorView *_activity;
    UIButton *_takePhoto;
}

@end

@implementation DearViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disNotLink) name:IsNotLinkDear object:nil];
    }
    return self;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createTitleViewWith:@"亲爱的"];
    //创建头部视图
    [self createHeadView];
    //创建按钮视图
    [self createBtnView];
    //开启定位
    [self startLocation];
}
#pragma mark - 创建头部视图
- (void)createHeadView
{
    _btnView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,0,ScreenSize.width,ScreenSize.height - 64 - 49)];
    _btnView.showsHorizontalScrollIndicator = NO;
    _btnView.showsVerticalScrollIndicator = NO;
    _btnView.contentSize = CGSizeMake(ScreenSize.width, (BtnHeight*2+SpaceMargin*3) + HeadHeight);
    [self.view addSubview:_btnView];

    
    _headImageView = [[UIImageView alloc]init];
    //判断本地数据是否有图片
    if ([TPFileManager getPhotoStr:[NSString stringWithFormat:@"%@%@",DearAndMeImage,[DearUser sharedInstance].userId]]) {
        NSData * imageData = [TPFileManager getPhoto:[NSString stringWithFormat:@"%@%@",DearAndMeImage,[DearUser sharedInstance].userId]];
        _headImageView.image = [UIImage imageWithData:imageData];
    }else{
            _headImageView.image = ImageName(@"bgLogin");
    }
    _headImageView.userInteractionEnabled = YES;
    _headImageView.frame = CGRectMake(0, 0, ScreenSize.width,HeadHeight);
    [_btnView addSubview:_headImageView];
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, HeadHeight - ImageHeight, ScreenSize.width, ImageHeight)];
    topView.backgroundColor = RGBA(255, 255, 255, 0.5);
    [_headImageView addSubview:topView];
    
    locationImage = [[UIImageView alloc]initWithFrame:CGRectMake(12, 11, 15, 20)];
    locationImage.image = [UIImage imageNamed:@"smallL"];
    locationImage.hidden = YES;
    [topView addSubview:locationImage];
    
   _locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(locationImage.frame) + 5, 0, 200, ImageHeight)];
    _locationLabel.text = @"定位中.....";
    _locationLabel.font = FontSize(15);
    _locationLabel.textAlignment = NSTextAlignmentLeft;
    _locationLabel.textColor = [UIColor blackColor];
    [topView addSubview:_locationLabel];
    
    
    _activity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(12, 13, 11, 14)];
    [topView addSubview:_activity];

    
    
    _takePhoto = [UIButton buttonWithType:UIButtonTypeCustom];
    _takePhoto.frame = CGRectMake(ScreenSize.width - LeftMargin - 40, 0, 40, 36);
    [_takePhoto setImage:ImageName(@"take") forState:UIControlStateNormal];
    [_takePhoto addTarget:self action:@selector(headClick) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:_takePhoto];
    

    _headView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenSize.width, HeadHeight)];
    _headView.image = [UIImage imageNamed:@"relImage"];
    _headView.userInteractionEnabled = YES;
    [_btnView addSubview:_headView];
    
    UIImageView *oneImage = [[UIImageView alloc]initWithFrame:CGRectMake(LeftMargin, TopHeight, ScreenSize.width - LeftMargin*2, TextFieldHeight)];
    oneImage.image = [UIImage imageNamed:@"oneImage"];
    oneImage.userInteractionEnabled = YES;
    [_headView addSubview:oneImage];
    
    UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(LeftMargin, 11, 15, 20)];
    leftImageView.image = [UIImage imageNamed:@"login1"];
    leftImageView.contentMode = UIViewContentModeScaleAspectFit;
    [oneImage addSubview:leftImageView];
    
    _relTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftImageView.frame)+ LeftMargin/2, 0, oneImage.frame.size.width, TextFieldHeight)];
    _relTextField.textAlignment = NSTextAlignmentLeft;
    _relTextField.delegate = self;
    _relTextField.backgroundColor = [UIColor clearColor];
    _relTextField.placeholder = @"请输入关联手机号";
    _relTextField.font = FontSize(15);
    _relTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [oneImage addSubview:_relTextField];
    
    
    _relBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_relBtn setTitle:@"关联" forState:UIControlStateNormal];
    _relBtn.backgroundColor = SameColor;
    _relBtn.frame = CGRectMake(ScreenSize.width - LeftMargin - RelWidth , CGRectGetMaxY(oneImage.frame) + LeftMargin, RelWidth, RelHeight);
    _relBtn.layer.cornerRadius = 5;
    _relBtn.layer.masksToBounds = YES;
    _relBtn.tag = RelationTag;
    [_relBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    _relBtn.titleLabel.font = FontSize(15);
    [_headView addSubview:_relBtn];
    
    UILabel *relLabel = [[UILabel alloc] initWithFrame:CGRectMake(LeftMargin, CGRectGetMaxY(oneImage.frame) + LeftMargin, 200, RelHeight)];
    relLabel.text = @"体验全部功能请关联另一半";
    relLabel.font = FontSize(15);
    relLabel.textAlignment = NSTextAlignmentLeft;
    relLabel.textColor = [UIColor blackColor];
    [_headView addSubview:relLabel];
    
    
    if ([[DearUser sharedInstance].linkFlag integerValue] == 1) {
        _headView.hidden = YES;
        _headImageView.hidden = NO;
        
    }else {
        _headImageView.hidden = YES;
        _headView.hidden = NO;
    }
}


- (void)startLocation{
//    LocationTool *tool = [LocationTool share];
//    tool.delegate = self;
    UploadRequest *tool = [UploadRequest sharedInstance];
    tool.delegate = self;
    [tool getLocation];
    [_activity startAnimating];
}

- (void)getLocationAddress:(NSString *)address{
    [_activity stopAnimating];
    [_activity hidesWhenStopped];
    _locationLabel.text = address;
    locationImage.hidden = NO;
}

#pragma mark - 创建按钮视图
- (void)createBtnView
{
    
    CGFloat width = (ScreenSize.width - SpaceMargin * 3)/2;
    
    _whereBtn = [[CustomButton alloc]initWithFrame:CGRectMake(SpaceMargin,SpaceMargin + HeadHeight,width,BtnHeight) withTitle:@"亲爱的在哪里" withImage:@"dear_tab_found_one"];
    _whereBtn.backgroundColor = RGBA(125, 202, 235, 1);
    _whereBtn.tag = WhereTag;
    [_whereBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_btnView addSubview:_whereBtn];
    
    _lookBtn = [[CustomButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_whereBtn.frame) + SpaceMargin,SpaceMargin+ HeadHeight,width,BtnHeight) withTitle:@"查看亲爱的轨迹" withImage:@"dear_tab_found_two"];
    _lookBtn.backgroundColor = RGBA(165, 219, 117, 1);
    _lookBtn.tag = LookTag;
     [_lookBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_btnView addSubview:_lookBtn];
    
    _sexesBtn = [[CustomButton alloc]initWithFrame:CGRectMake(SpaceMargin,CGRectGetMaxY(_whereBtn.frame) +SpaceMargin,width,BtnHeight) withTitle:@"两性健康" withImage:@"dear_tab_found_three"];
    _sexesBtn.backgroundColor = RGBA(254, 214, 112, 1);
    _sexesBtn.tag = SexesTag;
     [_sexesBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_btnView addSubview:_sexesBtn];
    
    
    _emotionalBtn = [[CustomButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_sexesBtn.frame) + SpaceMargin,CGRectGetMaxY(_whereBtn.frame) +SpaceMargin,width,BtnHeight) withTitle:@"情感健康" withImage:@"dear_tab_found_four"];
    _emotionalBtn.backgroundColor = RGBA(249, 129, 109, 1);
    _emotionalBtn.tag = EmotionalTag;
     [_emotionalBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_btnView addSubview:_emotionalBtn];
}

#pragma mark -按钮点击事件
- (void)btnClick:(UIButton *)btn
{
    switch (btn.tag) {
        case SexesTag:
        {
            SexViewController * svc = [[SexViewController alloc]init];
            svc.type = @"0";
            svc.titleStr = @"两性健康";
            svc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:svc animated:YES];
        }
            break;
        case WhereTag:{
            NSNumber *linkFlag = [DearUser sharedInstance].linkFlag;
            if ([linkFlag integerValue] == 0) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"还没关联亲爱的" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
            
            LocViewController *lvc = [[LocViewController alloc]init];
            lvc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:lvc animated:YES];
            
        }
            break;
        case LookTag:{
            NSNumber *linkFlag = [DearUser sharedInstance].linkFlag;
            if ([linkFlag integerValue] == 0) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"还没关联亲爱的" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
            LocPathViewController *lvc = [[LocPathViewController alloc]init];
            lvc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:lvc animated:YES];
        }
            break;
        case EmotionalTag:{
            SexViewController * svc = [[SexViewController alloc]init];
            svc.type = @"1";
            svc.titleStr = @"情感夜话";
            svc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:svc animated:YES];
        }
            break;
            
        case RelationTag:
        {
            [self relationOther];
        }
            break;
        default:
            break;
    }
}

#pragma mark - 关联其他账号
- (void)relationOther
{
    NSString *relationName = [_relTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (relationName.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"输入关联账号" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    NSDictionary *dict = @{@"userName1":[DearUser sharedInstance].userName,@"userName2":relationName};
    NSString *url = [ServerUrl stringByAppendingFormat:@"/%@",DearHttpLinkMobile];
    [[HttpRequest sharedInstance] POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [DearLoadingView hideHUD];
        if (responseObject) {
            NSDictionary *dict = (NSDictionary *)responseObject;
            if ([dict[@"Result"] integerValue] == 0)
            {
                //关联成功
                [DearLoadingView showTips:dict[@"Message"]];
                [self linkSuccess];
            }else {
                [DearLoadingView showTips:dict[@"Message"]];
            }
        }else{
            [DearLoadingView showTips:@"获取失败"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [DearLoadingView hideHUD];
        [DearLoadingView showTips:error];
    }];
    
    
}

#pragma mark - 本地上传图片
- (void)headClick{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"本地相册",@"相机拍照",@"回复默认", nil];
    [sheet showInView:self.view];
}
#pragma mark - sheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
            imagePicker.delegate = self;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//设置来源
            imagePicker.allowsEditing=YES;//允许编辑
            [self presentViewController:imagePicker animated:NO completion:nil];
        }
    }else if(buttonIndex == 1){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
            imagePicker.delegate = self;
            imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
            imagePicker.cameraDevice=UIImagePickerControllerCameraDeviceRear;//选择摄像头
            imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;//摄像头模式
            [self presentViewController:imagePicker animated:NO completion:nil];
        }else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该设备没有照相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
        }
    }else if(buttonIndex  == 2){
        _headImageView.image = ImageName(@"bgLogin");
        [TPFileManager deleteImageData:[NSString stringWithFormat:@"%@%@",DearAndMeImage,[DearUser sharedInstance].userId]];
    }
}

#pragma mark- UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果是拍照
        UIImage *image;
        //如果允许编辑则获得编辑后的照片，否则获取原始照片
        if (picker.allowsEditing) {
            image=[info objectForKey:UIImagePickerControllerEditedImage];//获取编辑后的照片
        }else{
            image=[info objectForKey:UIImagePickerControllerOriginalImage];//获取原始照片
        }
        [picker dismissViewControllerAnimated:YES completion:^{
            NSData *data = UIImageJPEGRepresentation(image, 0.5);
            //保存文件中
            [TPFileManager savePhotoFor:data nameStr:[NSString stringWithFormat:@"%@%@",DearAndMeImage,[DearUser sharedInstance].userId]];
            _headImageView.image = image;
        }];
    }
}

#pragma mark - 关联成功
- (void)linkSuccess
{
    //隐藏按钮
    _headImageView.hidden = NO;
    _headView.hidden = YES;
    //更改状态
    [DearUser sharedInstance].linkFlag = [NSNumber numberWithInt:1];
}
#pragma mark - 是否已经关联
- (void)disNotLink
{
    _relTextField.text  = @"";
    _headImageView.hidden = YES;
    _headView.hidden = NO;
   
}

- (void)keyboardHidden{
    [_relTextField resignFirstResponder];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

@end
